package com.hlkj.warboot.module_wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.hlkj.warboot.configurer.util.HttpHelperUtil;
import com.hlkj.warboot.configurer.util.ResponseUtil;

import java.text.MessageFormat;

/**
 * @Description:
 * @Author: lixing
 * @Date: 2020/6/26 17:42
 */
public class DemoUtil {
    /**
     * @Description 获取AccessToken
     * @Author lixing
     * @Date 2021/3/9 21:13
     */
    public static JSONObject getAccessToken(String appid, String secret) {
        String tokenUrl = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret);
        String accessTokenResponseStr = HttpHelperUtil.sendRequestHttps(tokenUrl, "GET",null);
        // 响应参数
        // {"errcode":40125,"errmsg":"invalid appsecret, view more at http:\/\/t.cn\/RAEkdVq rid: 604773a3-5a985f18-248602c5"}
        // {"access_token":"42_gLYd0R5ADAJDI","expires_in":7200}
        JSONObject accessTokenResponseObj = JSONObject.parseObject(accessTokenResponseStr);
        if (accessTokenResponseObj.containsKey("errcode")) {
            return ResponseUtil.fail(accessTokenResponseObj.getString("errmsg"));
        }
        String accessToken = accessTokenResponseObj.getString("access_token");
        getJsapiTicket(accessToken);
        return ResponseUtil.success(accessToken);
    }

    /**
     * @Description 获取JSAPI_TICKET
     * @Author lixing
     * @Date 2021/3/9 21:13
     */
    public static JSONObject getJsapiTicket(String accessToken) {
        String jsapiTicketUrl = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", accessToken);
        String jsapiTicketResponseStr = HttpHelperUtil.sendRequestHttps(jsapiTicketUrl, "GET",null);
        //
        JSONObject jsapiTicketResponseObj = JSONObject.parseObject(jsapiTicketResponseStr);
        if (jsapiTicketResponseObj.containsKey("errcode") && !"0".equals(jsapiTicketResponseObj.getString("errcode"))) {
            return ResponseUtil.fail(jsapiTicketResponseObj.getString("errmsg"));
        }
        String jsapiTicket = jsapiTicketResponseObj.getString("ticket");
        WeChatSignForJsapiTicket.sign(jsapiTicket, "http://www.baidu.com");
        return ResponseUtil.success(jsapiTicket);
    }

    public static void main(String[] args) {
        String appid = "wx6716d63161774c48";
        String secret = "d2cf2bc4a6a4e02de09f335f0e303b6d";
        JSONObject accessTokenObj = getAccessToken(appid, secret);


    }
}